<?php

class InvoiceEmpController extends Controller
{

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/customer';

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array('accessControl', // perform access control for CRUD operations
            array('application.filters.RequireLoginFilter', ), );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(array('allow',
            // allow all users to perform 'index' and 'view' actions

        'users' => array('@'), ), array('deny', // deny all users
            'users' => array('*'), ), );
    }

    public function actionSaveBatch()
    {
        if (isset($_POST['invoice']) && isset($_POST['data'])) {
            $invoice = $_POST['invoice'];
            $invoiceModel=Invoice::model()->findByPk($invoice);
          
            if ($invoiceModel==NULL || $invoiceModel->isEditable() === false) {
                return false;
            }
            $data = $_POST['data'];
            foreach ($data as $item) {
                if (isset($item[0]) && $item[0] == 'delete') {
                    Yii::app()->db->createCommand()->delete('tbl_invoice_emp',
                        'invoice=:invoice AND id=:id', array('invoice' => $invoice, 'id' => $item[1]));
                } else {
                    if (isset($item['id']) && $item['id'] != 0) {
                        $model = InvoiceEmp::model()->findByPk($item['id']);
                    } else {
                        $model = new InvoiceEmp;
                    }
                    if ($model != null) {
                        $model->invoice = $invoice;
                        $model->credit = $item['credit'];
                        $model->employeeno = $item['employeeno'];
                        $model->regularhours = $item['regularhours'];
                        $model->overtimehours = $item['overtimehours'];
                        $model->laboramount = $item['laboramount'];
                        $model->overhead = $item['overhead'];
                        if ($model->save()) {
                            echo "Successful";
                        } else {
                            echo json_encode($model->getErrors());
                        }
                    }

                }
            }
        }
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $model = new InvoiceEmp;


        $model->credit = 100;
        if (isset($_POST)) {

            $model->attributes = $_POST;
            $model->status = 1;
            if ($model->save()) {
                echo json_encode(array('success' => true, 'msg' => "Saving successful"));
            } else {
                echo json_encode(array('success' => false, 'errors' => $model->getErrors()));
            }
        }
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate()
    {


        if (isset($_POST) && isset($_POST['id']) && $_POST['id'] != null) {
            //update employee
            $model = $this->loadModel($_POST['id']);
            if ($model == null)
                Yii::app()->end();
            $model->attributes = $_POST;

            if ($model->save()) {
                echo json_encode(array('success' => true, 'msg' => "Saving successful"));
            } else {
                echo json_encode(array('success' => false, 'errors' => $model->getErrors()));
            }
        } else {
            //insert employee
            $model = new InvoiceEmp;


            $model->credit = 100;
            if (isset($_POST)) {

                $model->attributes = $_POST;
                $model->status = 1;
                if ($model->save()) {
                    echo json_encode(array('success' => true, 'msg' => "Saving successful"));
                } else {
                    echo json_encode(array('success' => false, 'errors' => $model->getErrors()));
                }
            }
        }

    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {

        $model = $this->loadModel($id);
        $invoice = $model->invoice;
        $model->delete();

    }

    /**
     * Lists all models.
     */
    public function actionIndex($invoice)
    {

        $model = Invoice::model()->findByPk($invoice);
        $location = Locations::model()->find('locno=:locno', array('locno' => $model->
            locno));
        $customer = Customers::model()->find('custno=:custno', array('custno' => $location->
            custno));

        outputJsByList(Employees::model()->getEmployeeList(), 'employee');
        $this->render('index', array('location' => $location, 'customer' => $customer,
            'model' => $model));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model = InvoiceEmp::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    //TODO move this code to model
    public function actionList($invoice, $page = 1, $sort = null)
    {
        //we decrease $page by 1 because in Extjs first page is 1, but in our sql first page is 0;
        if ($page > 0)
            $page--;
        $order = CJSON::decode($sort);
        $employers = new CActiveDataProvider('InvoiceEmp', array(
            'criteria' => array(
                'condition' =>"invoice=:invoice", 
                'params' => array(
                    'invoice' => $invoice
                    ), 
                'order' => isset($sort) ?$order[0]['property'] . ' ' . $order[0]['direction'] : null, ), 
            'pagination' =>array(
                'pageSize' => 20, 
                'currentPage' => $page, 
                ), 
            ));

        $empList = array();
        if ($employers->getTotalItemCount() > 0) {
            $empList['totalCount'] = $employers->getTotalItemCount();
            $empList['type'] = 'Items';
            foreach ($employers->getData() as $i => $item) {
                $empList['data'][$i] = $item->getAttributes();
                if ($item->employee != null) {
                    $empList['data'][$i]['employeetext'] = $item->employee->firstname . ' ' . $item->
                        employee->lastname;
                }
            }
            echo json_encode($empList);
        }
        Yii::app()->end();
    }

    /**
     * @return JSON with technician data
     */
    public function actionGetTechnicianData($id)
    {

        $model = Employees::model()->findByPk($id);
        $data = array();
        $data['hrate'] = $model->hrrate;
        $data['overhead'] = $model->overhead;
        echo json_encode($data);
        Yii::app()->end();
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'invoice-emp-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
